//
// Created on 2024/1/2.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".

#ifndef EGL_RENDER_CONTEXT_H
#define EGL_RENDER_CONTEXT_H

#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES3/gl3.h>
#include <GLES3/gl32.h>
#include <GLES2/gl2ext.h>

namespace webrtc {

const char *GetEglErrorString();

class EGLRenderContext {
public:
    EGLRenderContext();
    ~EGLRenderContext() noexcept;

    EGLRenderContext(const EGLRenderContext &) = delete;
    void operator=(const EGLRenderContext &) = delete;
    EGLRenderContext(const EGLRenderContext &&) = delete;
    void operator=(const EGLRenderContext &&) = delete;

    bool Init(EGLContext eglContext = EGL_NO_CONTEXT);
    bool IsEglContextReady() const { return eglContext_ != EGL_NO_CONTEXT; }

    EGLDisplay GetEGLDisplay() const { return eglDisplay_; }
    EGLContext GetEGLContext() const { return eglContext_; }

    EGLSurface CreateEglSurface(EGLNativeWindowType surface, const EGLint *attribList = nullptr);
    EGLSurface CreatePBufferEglSurface(const EGLint *attribList = nullptr);
    void DestroyEglSurface(EGLSurface surface);

    void MakeCurrent(EGLSurface surface = EGL_NO_SURFACE) const;
    void SwapBuffers(EGLSurface surface) const;

private:
    void SetupEglExtensions();

protected:
    EGLDisplay eglDisplay_ = EGL_NO_DISPLAY;
    EGLContext eglContext_ = EGL_NO_CONTEXT;
    EGLConfig config_ = nullptr;

    bool hasEglSurfacelessContext_ = false;
    bool hasEglBufferAge_ = false;
    bool hasEglPartialUpdate_ = false;
    PFNEGLSETDAMAGEREGIONKHRPROC eglSetDamageRegionFunc_ = nullptr;
    PFNEGLSWAPBUFFERSWITHDAMAGEKHRPROC eglSwapBuffersWithDamageFunc_ = nullptr;
    PFNEGLCREATEIMAGEKHRPROC eglCreateImageFunc_ = nullptr;
    PFNGLEGLIMAGETARGETTEXTURE2DOESPROC eglImageTargetTexture2DOESFunc_ = nullptr;
};
} // namespace webrtc
#endif // EGL_RENDER_CONTEXT_H
